#include "xcall.h"
#ifdef WIN32
#include <Objbase.h>
#endif
#include <string.h>
#include <stdio.h>
#include "xmessage.h"
#include "xrequest.h"
#include "xresponse.h"
#include "msg.h"
#include "xheader.h"
#include "xcontent.h"
#include "xdeepcontent.h"
#include "xtransaction.h"
#include "libxsip.h"
#include "xdialog.h"
#include "xcommand.h"

XSIPCall::XSIPCall()
{
#ifdef WIN32
	GUID guid;
	CoCreateGuid(&guid);
	sprintf(m_guid, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
		guid.Data1
		, guid.Data2
		, guid.Data3
		, guid.Data4[0], guid.Data4[1]
	, guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5]
	, guid.Data4[6], guid.Data4[7]);
#endif
	m_receiver = NULL;
	m_transaction = NULL;
}

XSIPCall::~XSIPCall()
{
	if (m_transaction)
	{
		XSIPEngine::getCurrentThreadEngine()->removeTransaction(m_transaction);
		delete m_transaction;
	}
	m_transaction = NULL;
}

void* XSIPCall::getObject(const char* name) const
{
	if (strcmp(name, "XSIPCall") == 0)
		return const_cast<XSIPCall*>(this);
	else
		return XSIPEvent::getObject(name);
}

void XSIPCall::setDataReceiver(XSIPDataReceiver* receiver)
{
	m_receiver = receiver;
}

XSIPDataReceiver* XSIPCall::getDataReceiver()
{
	return m_receiver;
}

XSIPTransaction* XSIPCall::createTransaction(XSIPRequest* request, XSIPTransport* transport)
{
	return NULL;
}

XSIPResponse* XSIPCall::createResponse(XSIPTransaction* transaction, XSIPRequest* request, int code)
{
	if (transaction->getResponse())
	{
		return transaction->getResponse();
	}
	XSIPResponse *response = new XSIPResponse();
	XSIPHeader *header = new XSIPHeader();
	XSIPContent *content = new XSIPDeepContent();
	response->setHeader(header);
	response->setContent(content);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_CSEQ);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_VERSION);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_TRANSACTION_ID);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_CALL_ID);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_SESSION_ID);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_METHOD);
	header->copy(request->getHeader(), XSIP_MSG_HEADER_SUBMETHOD);
	header->addHeader(XSIP_MSG_HEADER_STATUS_CODE, code);
	response->setTransaction(transaction);
	transaction->setOwner((XSIPCall*) getObject("XSIPCall"));
	transaction->setResponse(response);
	transaction->setRequest(request);
	m_transaction = transaction;
	return response;
}

char* XSIPCall::getCallId()
{
	return m_guid;
}

void XSIPCall::setCallId(char* id)
{
	sprintf(m_guid, "%s", id);
}

